import { defineStore } from 'pinia'
import {
  accountLogin,
  getUserInfoById,
  getUserMenusByRoleId
} from '@/service/login/login'
import type { ILoginAccount, ILoginAccountState } from '@/types'
import { localCache } from '@/utils/cache'
import { TOKEN, USERINFO, USERMENU } from '@/types/constant'
import router from '@/router'
import { mapMenuListToPermissions, mapMenusToRoutes } from '@/utils/map-menus'
import { useMainStore } from '../main/main'

export const useLoginStore = defineStore('login_store', {
  state: (): ILoginAccountState => ({
    id: 0,
    token: '',
    name: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  }),
  actions: {
    async fetchLoginAccountAction(account: ILoginAccount) {
      const res = await accountLogin(account)
      this.id = res.data.id
      this.token = res.data.token
      this.name = res.data.name

      // 缓存token
      localCache.setCache(TOKEN, this.token)

      // 获取登录用户信息
      const userInfoResult = await getUserInfoById(this.id)
      this.userInfo = userInfoResult.data
      localCache.setCache(USERINFO, this.userInfo)

      // 根据角色请求用户的权限菜单
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      this.userMenus = userMenusResult.data
      localCache.setCache(USERMENU, this.userMenus)

      // 获取登录用户的所有按钮的权限
      const permissions = mapMenuListToPermissions(this.userMenus)
      this.permissions = permissions

      // 动态添加路由
      const routes = mapMenusToRoutes(this.userMenus)
      routes.forEach((route) => router.addRoute('main', route))

      // 获取roles/departments数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()

      // 登录成功跳转main页面
      router.push('/main')
    },
    // 动态路由
    loadLocalCacheAction() {
      // 用户进行默认刷新加载数据
      const token = localCache.getCache(TOKEN)
      const userInfo = localCache.getCache(USERINFO)
      const userMenus = localCache.getCache(USERMENU)
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 获取roles/departments数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
        // 获取登录用户的所有按钮的权限
        const permissions = mapMenuListToPermissions(this.userMenus)
        this.permissions = permissions
        // 动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})
